package com.yanqu.road.queue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.logAnalysis.ItemChangeDetail;
import com.yanqu.road.entity.logAnalysis.RoleShopBuy;
import com.yanqu.road.logic.service.ItemChangeDetailService;
import com.yanqu.road.logic.service.RoleShopBuyService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.*;


/**
 * @author duli
 * @version 1.0
 * @date 2020/9/9 14:11
 * @Description build 日志分析数据
 */
@Component
public class LogAnalysisMgr {
    private static final Logger log = LogManager.getLogger(LogAnalysisMgr.class.getName());

    private static LogAnalysisMgr logAnalysisMgr;
    private static final int pollSize = 1000000;

    @PostConstruct
    public void init() {
        logAnalysisMgr = this;
    }

    @Autowired
    private ItemChangeDetailService itemChangeDetailService;
    @Autowired
    private RoleShopBuyService roleShopBuyService;

    /**
     * 分发数据到对应的service
     */
    public static void dispatchGameLogData() {
        JSONArray jsonArray = new JSONArray();
        try {
            jsonArray = LogAnalysisReceiveQueue.poll(pollSize);
            List<ItemChangeDetail> itemChangeDetails = new ArrayList<>();
            List<RoleShopBuy> roleShopBuyList = new ArrayList<>();
            if (!jsonArray.isEmpty()) {
                jsonArray.stream().forEach(obj -> {
                    JSONObject jsonobject = (JSONObject) JSON.toJSON(obj);
                    if (jsonobject.get("event").equals("change")) {
                        ItemChangeDetail change = JSON.parseObject(String.valueOf(jsonobject), ItemChangeDetail.class);
                        itemChangeDetails.add(change);
                    } else if (jsonobject.get("event").equals("shopbuy")) {
                        RoleShopBuy roleShopBuy = JSON.parseObject(String.valueOf(jsonobject), RoleShopBuy.class);
                        roleShopBuyList.add(roleShopBuy);
                    }

                });
            }
            if (!CollectionUtils.isEmpty(itemChangeDetails)) {
                logAnalysisMgr.itemChangeDetailService.batchBeforeSave(itemChangeDetails);
            }
            if (!CollectionUtils.isEmpty(roleShopBuyList)) {
                logAnalysisMgr.roleShopBuyService.batchBeforeSave(roleShopBuyList);
            }

        } catch (Exception e) {
            log.error("命令[批量上报]处理异常...", e);
        } finally {
            log.info("命令[批量存入数据库]成功:" + jsonArray.size());
        }

    }

}
